<?php
/**
 * Created by PhpStorm.
 * User: WangYuanHong
 * Date: 2017/12/5 0005
 * Time: 上午 9:20
 */

namespace app\services;


use yii\base\Exception;
use app\utils\HttpUtil;

class CookieServerService
{
    public $data = '';
    public $apiVersion = '2.0';
    public $cookieServerUrl = 'http://cookieserver.qingtaoke.com/index.php?r=api/get-coupon-info&app_name=';
    public $appName = 'qtk_admin查询';
    public $quan_id;

    public function __construct($apiVersion = '2.0',$appName = 'qtk_admin查询')
    {
        $this->apiVersion = $apiVersion;
        $this->appName = $appName;
    }

    public function setApiVersion($apiVersion = '2.0')
    {
        $this->apiVersion = $apiVersion;
    }

    public function setAppName($appName = 'qtk_admin查询')
    {
        $this->appName = $appName;
    }

    public function init($aid,$sid,$gid)
    {
        $this->data = '';
        $cookieServerUrl = $this->cookieServerUrl . $this->appName . '&v=' . $this->apiVersion . '&id=' . $aid;
        $cookieServerUrl = $cookieServerUrl . '&gid=' . $gid . '&sellerId=' . $sid;
        $this->quan_id = $aid;
        $str_item = HttpUtil::requestHttp($cookieServerUrl,"aaaa=xxx");
        if(empty($str_item)){
            throw new Exception("从cookieServer获取券信息失败 version={$this->apiVersion}");
        }
        $arr_item = json_decode($str_item,true);
        if(JSON_ERROR_NONE !== json_last_error()){
            throw new Exception("券信息解析失败 version={$this->apiVersion} dataStr={$str_item}");
        }
        if($arr_item['status'] != 0){
            if(isset($arr_item['msg'])){
                throw new Exception($arr_item['msg']);
            }
            throw new Exception("通过轻淘客接口读取券数据出错");
        }

        $this->data = $arr_item['data'];
        if($this->apiVersion != '2.0' && !isset($this->data['discount'])){
            $this->data = '';
            throw new Exception("券数据不正确 {$str_item}");
        }
        if($this->apiVersion == '2.0' && !isset($this->data['amount'])){
            $this->data = '';
            throw new Exception("券数据不正确 {$str_item}");
        }
    }

    public function startTime(){
        if($this->apiVersion == '2.0'){
            return $this->data['effectiveStartTime'];
        }
        elseif($this->apiVersion == '1.0'){
            return $this->data['startTime'];
        }
        elseif($this->apiVersion == '3.0'){
            return $this->data['coupon_start_time'];
        }
        return false;
    }

    public function endTime(){
        if($this->apiVersion == '2.0'){
            return $this->data['effectiveEndTime'];
        }elseif($this->apiVersion == '1.0'){
            return $this->data['endTime'];
        }elseif($this->apiVersion == '3.0'){
            return $this->data['coupon_end_time'];
        }
        return false;
    }

    public function quan_id(){
        return $this->quan_id;
    }

    public function shopNick(){
        if($this->apiVersion == '2.0'){
            return $this->data['shopName'];
        }
        return false;
    }

    public function quan_tiaojian(){
        if($this->apiVersion == '2.0'){
            return floatval($this->data['startFee']);
        }elseif ($this->apiVersion == '1.0'){
            return floatval($this->data['startFee']/100);
        }elseif($this->apiVersion == '3.0'){
            return $this->data['coupon_start_fee'];
        }
        return false;
    }

    public function quan_price(){
        if($this->apiVersion == '2.0'){
            return floatval($this->data['amount']);
        }elseif($this->apiVersion == '1.0'){
            return floatval($this->data['discount']/100);
        }elseif($this->apiVersion == '3.0'){
            return $this->data['coupon_amount'];
        }
        return false;
    }

    public function quan_total(){
        if($this->apiVersion == '3.0'){
            return $this->data['coupon_total_count'];
        }
        return 0;
    }

    public function quan_over(){
        if($this->apiVersion == '3.0'){
            return $this->data['coupon_total_count'] - $this->data['coupon_remain_count'];
        }
        return 0;
    }

    public function quan_num(){
        if($this->apiVersion == '3.0'){
            return $this->data['coupon_remain_count'];
        }
        return 0;
    }

    public function getCouponType()
    {
        if(empty($this->data)){
            return false;
        }
        if($this->apiVersion != '1.0'){
            return false;
        }
        if(!isset($this->data['couponType'])){
            return false;
        }
        return $this->data['couponType'];
    }

    public function getIsAble()
    {
        if(empty($this->data)){
            return false;
        }
        if($this->apiVersion == '1.0'){
            if(!isset($this->data['couponType'])){
                return false;
            }
            if($this->data['couponType'] == 1){
                return 0;
            }

            return 1;
        }
        elseif($this->apiVersion == '2.0'){
            if(!isset($this->data['retStatus'])){
                return false;
            }

            if($this->data['retStatus'] == 0){
                return 1;
            }

            return 0;
        }
        elseif($this->apiVersion == '3.0'){
            if(isset($this->data['coupon_amount'])){
                return 1;
            }
            return 0;
        }

        return 0;
    }

    public function instance($aid,$sid,$gid)
    {
        $key = "qtk_admin2_coupon_info_".$aid;
        $data = \Yii::$app->cache->get($key);
        if($data !== false){
            return $data;
        }
        try{
            $this->init($aid,$sid,$gid);
        }catch (Exception $e){
            $this->setApiVersion('1.0');
            $this->setAppName('qtk_admin查询');
            $this->init($aid,$sid,$gid);
        }
        \Yii::$app->cache->set($key,$this,600);
        return $this;
    }


    public static function unionInfo($sid,$aid)
    {
        $sign = '0ade00b0ad98a04109479ea99e19f280';
        $t = time();
        $data = json_encode(['sellerId' => $sid, 'activityId' => $aid]);

        $url = "https://acs.m.taobao.com/h5/mtop.alimama.union.hsf.mama.coupon.get/1.0/?jsv=2.3.16&";
        $url.= "appKey=12574478&t=1520822486354&sign={$sign}&api=mtop.alimama.union.hsf.mama.coupon.get&";
        $url.= "AntiCreep=true&AntiFlood=true&v=1.0&data=".$data;

        $ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0';
        $ip = self::createXfIp();
        $headers = [
            'X-Forwarded-For: '.$ip,
            'user-agent: ' . $ua,
        ];
        $sendArr = [
            'url'=>$url,
            'headers' => $headers,
            'isShowHeader' => true,
            "referer:https://uland.taobao.com/quan/detail?sellerId={$sid}&activityId={$aid}"
        ];

        HttpUtil::sendHttpsRequest($sendArr);
        $responseTwoHeader = self::getHeaderParams(HttpUtil::$responseHeader);
        if(!isset($responseTwoHeader['Set-Cookie'])){
            return false;
        }

        $sendCookieArr = [];
        foreach ($responseTwoHeader['Set-Cookie'] as $cookieStr){
            if(empty($cookieStr)){
                continue;
            }
            $cookieArr = explode(';',$cookieStr);
            $cookieTwoArr = explode('=',$cookieArr[0]);
            $sendCookieArr[$cookieTwoArr[0]] = $cookieTwoArr[1];
        }

        if(!isset($sendCookieArr['_m_h5_tk']) || empty($sendCookieArr['_m_h5_tk'])){
            return false;
        }
        $h5tkArr = explode('_',$sendCookieArr['_m_h5_tk']);
        if(count($h5tkArr) == 1) {
            return false;
        }

        $t = time();
        $sign = md5($h5tkArr[0] . '&' . $t . '&12574478&' . $data);
        $data = urlencode($data);
        $url = "https://acs.m.taobao.com/h5/mtop.alimama.union.hsf.mama.coupon.get/1.0/?jsv=2.3.16&";
        $url.= "appKey=12574478&t={$t}&sign={$sign}&api=mtop.alimama.union.hsf.mama.coupon.get&";
        $url.= "AntiCreep=true&AntiFlood=true&v=1.0&data=".$data;
        $sendArr['url'] = $url;
        $sendCookieStr = '';
        foreach ($sendCookieArr as $cookieKey=>$cookieVal){
            $sendCookieStr .= $cookieKey.'='.$cookieVal.';';
        }
        $headers = [
            'X-Forwarded-For: '.$ip,
            'cookie: ' . $sendCookieStr,
            'user-agent: ' . $ua,
            "referer:https://uland.taobao.com/quan/detail?sellerId={$sid}&activityId={$aid}"
        ];

        $sendArr['headers'] = $headers;

        HttpUtil::$responseHeader = '';
        HttpUtil::$responseBody = '';
        HttpUtil::sendHttpsRequest($sendArr);

        if(empty(HttpUtil::$responseBody)){
            return false;
        }

        $dataArr = json_decode(HttpUtil::$responseBody,true);
        if(!is_array($dataArr)){
            return false;
        }

        if(!isset($dataArr['data']['result'])){
            return false;
        }

        if(!isset($dataArr['data']['result']['retStatus'])){
            return false;
        }

        if($dataArr['data']['result']['retStatus'] == 8){
            return false;
        }

        return $dataArr['data']['result'];
    }

    public function setData($data){
        $this->data = $data;
    }

    public static function createXfIp()
    {
        $ip1 = rand(100,200);
        $ip2 = rand(100,200);
        $ip3 = rand(100,200);
        $ip4 = rand(100,200);

        $ip = $ip1.'.'.$ip2.'.'.$ip3.'.'.$ip4;
        return $ip;
    }

    public static function getHeaderParams($headerString){
        $headerArr = explode("\r\n",$headerString);
        $responseHeader = [];
        $responseHeader['Set-Cookie'] = [];
        foreach ($headerArr as $headerStr){
            $arr = explode(': ',$headerStr);
            if(!isset($arr[1])){
                continue;
            }
            if(isset($responseHeader[$arr[0]])){
                if($arr[0] == 'Set-Cookie'){
                    $responseHeader['Set-Cookie'][] = $arr[1];
                }
                continue;
            }
            $responseHeader[$arr[0]] = $arr[1];
        }
        return $responseHeader;
    }
}

